package org.example.util;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.ConfigManager;
import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.hunter.FileManager;
import com.baidu.ueditor.hunter.ImageHunter;
import com.baidu.ueditor.upload.Uploader;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class MyActionEnter extends ActionEnter {
    private ConfigManager configManager;
    private String actionType = "config";
    private HttpServletRequest request;

    public MyActionEnter(HttpServletRequest request, String rootPath) {
        super(request, rootPath);
        this.configManager = ConfigManager.getInstance(rootPath, "", "");
        this.request = request;
    }

    @Override
    public String invoke() {

        String actionType = request.getParameter("action");
        if(actionType == null || actionType.trim().length() == 0) {
            actionType = this.actionType;
        }

        if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
            return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
        }

        if ( this.configManager == null || !this.configManager.valid() ) {
            return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
        }

        State state = null;

        int actionCode = ActionMap.getType( actionType );

        Map<String, Object> conf = null;

        switch ( actionCode ) {

            case ActionMap.CONFIG:
                return this.configManager.getAllConfig().toString();

            case ActionMap.UPLOAD_IMAGE:
                conf = this.configManager.getConfig(actionCode);
                state = new Uploader( request, conf ).doExec();
                break;
            case ActionMap.UPLOAD_SCRAWL:
            case ActionMap.UPLOAD_VIDEO:
            case ActionMap.UPLOAD_FILE:
                conf = this.configManager.getConfig( actionCode );
                state = new Uploader( request, conf ).doExec();
                break;

            case ActionMap.CATCH_IMAGE:
                conf = configManager.getConfig( actionCode );
                String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
                state = new ImageHunter( conf ).capture( list );
                break;

            case ActionMap.LIST_IMAGE:
            case ActionMap.LIST_FILE:
                conf = configManager.getConfig( actionCode );
                int start = this.getStartIndex();
                state = new FileManager( conf ).listFile( start );
                break;

        }

        return state.toJSONString();

    }
}

